package com.amado.course42Socket.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 本机的IP:localhost,127.0.0.1,
 * 电脑局网的IP：192.168.0.99
 * Created by Administrator on 2018/8/7.
 */
public class S01HelloSocketStreamService {
	//端口号
	private int port = 8888;
	//服务端的对象
	private ServerSocket serverSocket;

	public S01HelloSocketStreamService() throws Exception {
		//建立了一个Socket服务器，端口是8888
		serverSocket = new ServerSocket(port);
		System.out.println("服务器启动!");
	}

	public void service() {
		//客户端的对象
		Socket socket = null;
		Scanner scanner = null;
		try {
			//等待接受请求
			socket = serverSocket.accept();
			//得到客户端的IP，端口
			System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
			//输出流
			PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);
			//客户端接收到  你已经连接到服务器
			printwriter.print("你已经连接到服务器");
			scanner = new Scanner(System.in);
			while(true){
				//把我的管制台输入的内容，输入出客户端 
				printwriter.println(scanner.nextLine());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (socket != null) {
				try {
					scanner.close();
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		S01HelloSocketStreamService server = new S01HelloSocketStreamService();
		server.service();
	}
}
